package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FieldValueFactorFunctionBuilder;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements cn.itcast.hotel.service.HotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        try {
            //创建请求SerchRequest对象
            SearchRequest request = new SearchRequest("hotel");
            SearchSourceBuilder source = request.source();

            buildBasicQuery(params, source);

            if (params.getSortBy().equals("score")) {
                source.sort("score", SortOrder.DESC);
            }
            if (params.getSortBy().equals("price")) {
                source.sort("price", SortOrder.ASC);
            }


            //设置分页的值
            source.from((params.getPage() - 1) * params.getSize());
            source.size(params.getSize());

            String location = params.getLocation();
            if (location != null && !location.equals("")) {
                request.source().sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS)
                );
            }

            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //判断location的值
            //封装对象
            PageResult pageResult = new PageResult();

            SearchHits hits = response.getHits();
            pageResult.setTotal(hits.getTotalHits().value);
            List<HotelDoc> list = new ArrayList<>();
            for (SearchHit hit : hits) {
                String s = hit.getSourceAsString();
                HotelDoc hotelDoc = JSON.parseObject(s, HotelDoc.class);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)) {
                    HighlightField highlightField = highlightFields.get("name");
                    String s1 = StringUtils.join(highlightField.getFragments());
                    hotelDoc.setName(s1);
                }
                Object[] sortValues = hit.getSortValues();
                if (sortValues.length > 0) {
                    hotelDoc.setDistance(sortValues[0]);
                }
                list.add(hotelDoc);
            }
            pageResult.setHotels(list);
            return pageResult;

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }


    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            SearchSourceBuilder source = request.source();
            buildBasicQuery(params, source);
            source.size(0);
            buildBasicAggregations(source);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Aggregations aggregations = response.getAggregations();
            List<String> brand = getAggByName("brandAgg",aggregations);
            List<String> city = getAggByName("cityAgg",aggregations);
            List<String> starName = getAggByName("starNameAgg",aggregations);
            Map<String,List<String>> resultMap = new HashMap<>();
            resultMap.put("brand",brand);
            resultMap.put("city",city);
            resultMap.put("starName",starName);
            return resultMap;
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("聚合查询失败");
        }
    }

    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            // 2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            // 3.发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hotel", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insertById(Long id) {
        try {
            // 0.根据id查询酒店数据
            Hotel hotel = getById(id);
            // 转换为文档类型
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<String> getAggByName(String aggName,Aggregations aggregations) {
        Terms aggResult = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = aggResult.getBuckets();
        List<String> resultList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets){
            resultList.add(bucket.getKeyAsString());
        }
        return resultList;
    }

    private void buildBasicAggregations(SearchSourceBuilder source) {
        source.aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(20));
        source.aggregation(AggregationBuilders.terms("cityAgg").field("city").size(20));
        source.aggregation(AggregationBuilders.terms("starNameAgg").field("starName").size(20));
    }

    private void buildBasicQuery(RequestParams params, SearchSourceBuilder source) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        String key = params.getKey();
        if (StringUtils.isBlank(key)) {
            //是空为true 查询全部
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("name");
            highlightBuilder.preTags("<em>");
            highlightBuilder.postTags("</em>");
            highlightBuilder.requireFieldMatch(false);
            source.highlighter(highlightBuilder);
        }
        //城市不为空
        if (StringUtils.isNotBlank(params.getCity())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        //星级不为空
        if (StringUtils.isNotBlank(params.getStarName())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        //品牌不为空
        if (StringUtils.isNotBlank(params.getBrand())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //价格不为空
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lt(params.getMaxPrice()));
        }
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQueryBuilder, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                        QueryBuilders.termQuery("isAD", true),
                        ScoreFunctionBuilders.weightFactorFunction(10)
                )
        }).boostMode(CombineFunction.MULTIPLY);
        source.query(functionScoreQuery);
    }


//    @Autowired
//    private HotelMapper hotelMapper;
//    @Override
//    public Hotel getById(Long id) {
//        return hotelMapper.getById(id);
//    }
}
